<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Tank</title>
    <style>
        .box{
            width: 640px;
            height: 640px;
            margin-left: auto;
            margin-right: auto;
            margin-top: 100px;
            background: url(/tankImg/grassland.png)no-repeat;
            position: relative;
        }
        .tank{
            position: absolute;
            top: 0;
            left: 0;
        }
        .btn{
            width: 156px;
            height: 66px;
            font-size: 27px;
            position: absolute;
            bottom: -66px;
            left: 242px;
        }
    </style>
</head>
<body>
    <div class="box">
        <img class="tank" src="tankImg/up.png" alt="">
        <button class="btn">禁用右键</button>
    </div>
    <script>
        let tank = document.querySelector(".tank");
        let box = document.querySelector(".box");
        let btn=document.querySelector(".btn");
        let speedX = 0, speedY = 0;

        let posObj = {
            x:640,
            y:640-42.5
        }
        let rotate = 0;
        function setPos(speedX, speedY){
            posObj.y += speedY;
            posObj.y = Math.max(posObj.y,0);
            posObj.y = Math.min(posObj.y,640-85);
            posObj.x += speedX;
            posObj.x = Math.max(posObj.x,18.5);//(长-宽)/2
            posObj.x = Math.min(posObj.x,640-76.5);//(长-宽)/2+宽
            tank.style.transform = `translate(${posObj.x += speedX }px,${posObj.y}px)  rotate(${rotate}deg)`;
        }
        setPos(speedX, speedY);

        setInterval(function(){
            setPos(speedX, speedY);
        },50);

        let right=1;
        btn.addEventListener("click",function(){
            right=0;
        })
        

        document.addEventListener("keydown",function(event){
            let key = event.key;
            if( key === "w"){
                speedY = -8;
                speedX = 0;
                rotate = 0;
            }
            else if( key === "s"){
                speedY = 8;
                speedX = 0;
                rotate = 180;
            }
            else if( key === "a"){
                speedX = -5;
                speedY = 0;
                rotate = 270;
            }
            else if( key === "d" && right==1){
                speedX = 5;
                speedY = 0;
                rotate = 90;
            }
        });

        document.addEventListener("keyup",function(event){
            let key = event.key;
            if( key === "w"){
                speedY = 0;
            }
            else if( key === "s"){
                speedY = 0;
            }
            else if( key === "a"){
                speedX = 0;
            }
            else if( key === "d"){
                speedX = 0;
            }
        });
    </script>
</body>
</html>